
//1. 公私钥对
//2. 公钥直接当成地址用(或者截取公钥前20位)
let fs = require('fs')

let EC = require('elliptic').ec

let ec = new EC('secp256k1')

let keypair = ec.genKeyPair()

function getPub(prv) { //根据私钥算出公钥
    return ec.keyFromPrivate(prv).getPublic('hex').toString()
}


//持久化获取 公私钥对
function generateKeys() {
    const fileName = './wallet.json'
    try {
        let res = JSON.parse(fs.readFileSync(fileName))
        if (res.prv && res.pub && getPub(res.prv) == res.pub) {
            keypair = ec.keyFromPrivate(res.prv)
            return res
        } else {
            throw 'not valid wallet.json'
        }
    } catch (error) {
        const res = {
            prv: keypair.getPrivate('hex').toString(),
            pub: keypair.getPublic('hex').toString()
        }
        fs.writeFileSync(fileName, JSON.stringify(res))
        return res
    };
}

//签名
function sign({ from, to, amout }) {
    const bufferMsg = Buffer.from(`${from}-${to}-${amount}`)
    let signature = Buffer.from(keypair.sign(bufferMsg).toDER()).toString()
    return signature
}

//校验签名
function verify({from,to,amount,signature},pub){
    const keypairTemp=ec.keyFromPublic(pub,'hex')
    const bufferMsg = Buffer.from(`${from}-${to}-${amount}`)
    return keypairTemp.verify(bufferMsg,signature)
}




